﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ggHD.WebSite.Controllers
{
    using ggHD.WebSite.MailService;
    using ggHD.WebSite.Models;
    using OpenPop.Mime;
    using System.Net.Mime;
    using System.Threading.Tasks;

    public class RawMailsController : Controller
    {
        readonly IMailService svc = new MailServiceClient();
        private const string ssMailPrefix = "GetMail_";

        public RawMailsController()
        {

        }

        // GET: /RawTickets/
        // [Authorize(Roles = "Admins")]
        public ActionResult Index()
        {
            return Index(DateTime.Today.AddDays(-7), DateTime.Today);
        }

        [HttpPost]
        // [Authorize(Roles="Admins")]
        public ActionResult Index(DateTime dateFrom, DateTime dateTo)
        {
            var mails = svc.GetMailHeaders(dateFrom, dateTo);

            ViewBag.DateFrom = dateFrom;
            ViewBag.DateTo = dateTo;

            return View("Index", mails);
        }

        [HttpPost]
        public PartialViewResult GetMail(long mailId)
        {
            var m = GetMailDetailViewModel(mailId);

            return PartialView(m);
        }

        private void ClearMailCache()
        {
            var keys = new List<string>();
            foreach (var item in Session.Keys)
            {
                if (item.ToString().Contains(ssMailPrefix))
                    keys.Add(item.ToString());
            }

            if (keys.Count > 4)
                foreach (var item in keys)
                {
                    Session.Remove(item);
                }
        }

        private MailDetailViewModel GetMailDetailViewModel(long mailId)
        {
            var ssMailId = ssMailPrefix + mailId;

            MailDetailViewModel m = null;

            if (Session[ssMailId] == null)
            {
                ClearMailCache();

                m = MailDetailViewModel.CreateFromRawMail(svc.GetRawMail(mailId));

                Session.Add(ssMailId, m);
            }
            else
                m = (MailDetailViewModel)Session[ssMailId];

            return m;
        }

        public ContentResult GetMailHtmlBody(long mailId)
        {
            var m = GetMailDetailViewModel(mailId);
            if (string.IsNullOrWhiteSpace(m.HtmlVersion))
                return null;

            return Content(m.HtmlVersion);
        }

        [HttpGet]
        public FileContentResult GetAttache(long mailId, int attache)
        {
            var msg = new Message(svc.GetRawMail(mailId).RawData);

            var file = msg.FindAllAttachments()[attache];

            return File(file.Body, MediaTypeNames.Application.Octet, file.FileName);
        }

        public ContentResult GetMailsCount()
        {
            return Content(svc.GetRawMailsCount().ToString());
        }

        [HttpPost]
        public async Task<ContentResult> LoadNewMails(DateTime from, DateTime to)
        {
            from = from.Date;
            to = to.Date;

               List<string> res = new List<string>();

               while (to >= from)
               {
                   int mc = 0;
                   try
                   {
                       mc = await svc.LoadRawMailsAsync(from);
                       from = from.AddDays(1);
                   }
                   catch
                   {
                       mc = -1;
                   }

                   res.Add(string.Format("За {0} загружено писем: {1}", from.ToString("dd.MM.yyyy"), mc));
               }

            return Content(string.Join("</br>", res.ToArray()));
        }

      
    }
}
